package org.example.Agricultural_33.controller;

import org.example.Agricultural_33.model.CommonResponse;
import org.example.Agricultural_33.model.bo.AgriculturalTraceabilityTransferOwnershipInputBO;
import org.example.Agricultural_33.model.bo.AgriculturalTraceabilityGetOwnershipTransferInputBO;
import org.example.Agricultural_33.service.AgriculturalTraceabilityService;
import org.fisco.bcos.sdk.transaction.model.dto.CallResponse;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 系统控制器
 */
@RestController
@RequestMapping("/api/system")
public class SystemController {

    @Autowired
    private AgriculturalTraceabilityService agriculturalTraceabilityService;

    /**
     * 获取合约信息
     * @return 合约信息
     */
    @GetMapping("/contract-info")
    public CommonResponse getContractInfo() {
        try {
            CallResponse response = agriculturalTraceabilityService.getContractInfo();
            return CommonResponse.ok(response.getReturnObject());
        } catch (Exception e) {
            return CommonResponse.fail("S001", e);
        }
    }

    /**
     * 获取合约所有者
     * @return 所有者地址
     */
    @GetMapping("/owner")
    public CommonResponse getOwner() {
        try {
            CallResponse response = agriculturalTraceabilityService.owner();
            return CommonResponse.ok(response.getReturnObject());
        } catch (Exception e) {
            return CommonResponse.fail("S002", e);
        }
    }

    /**
     * 转移合约所有权
     * @param newOwner 新所有者地址
     * @return 转移结果
     */
    @PostMapping("/transfer-ownership")
    public CommonResponse transferOwnership(@RequestParam String newOwner) {
        try {
            AgriculturalTraceabilityTransferOwnershipInputBO inputBO = new AgriculturalTraceabilityTransferOwnershipInputBO();
            inputBO.setNewOwner(newOwner);
            
            TransactionResponse response = agriculturalTraceabilityService.transferOwnership(inputBO);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("S003", e);
        }
    }

    /**
     * 查询所有权转移记录
     * @param txHash 交易哈希
     * @return 所有权转移记录
     */
    @GetMapping("/ownership-transfer")
    public CommonResponse getOwnershipTransfer(@RequestParam String txHash) {
        try {
            AgriculturalTraceabilityGetOwnershipTransferInputBO inputBO = new AgriculturalTraceabilityGetOwnershipTransferInputBO();
            inputBO.setTxHash(txHash);
            
            CallResponse response = agriculturalTraceabilityService.getOwnershipTransfer(inputBO);
            return CommonResponse.ok(response.getReturnObject());
        } catch (Exception e) {
            return CommonResponse.fail("S004", e);
        }
    }
} 